package threadPool;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 建议使用jdk原生线程池且参数自己配置
 *
 *
 * @author lyh
 */
@Configuration
public class ThreadPoolConfig {
    /***
     * 线程池
     * @return
     */
    @Bean
    public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutorMdcWrapper threadPoolTaskExecutor = new ThreadPoolTaskExecutorMdcWrapper();
        threadPoolTaskExecutor.setMaxPoolSize(32);
        threadPoolTaskExecutor.setCorePoolSize(8);
        threadPoolTaskExecutor.setKeepAliveSeconds(10);
        threadPoolTaskExecutor.setQueueCapacity(2000);
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPoolTaskExecutor");

        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        threadPoolTaskExecutor.setDaemon(true);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    /***
     * 回调专用线程池
     * @return
     */
    @Bean(name = "wxWorkEventCallThreadPool", autowire = Autowire.BY_NAME)
    public ExecutorService wxWorkEventCallThreadPool() {
        return new ThreadPoolExecutorMdcWrapper(1,
                8,
                4,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(64),
                new MyThreadFactory("wxWorkEventCallThreadPool"),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }


    /**
     * 学校同步任务(授权事件)
     * @return
     */
    @Bean(name = "syncExecutorService", autowire = Autowire.BY_NAME)
    public ExecutorService syncExecutorService() {
        return new ThreadPoolExecutorMdcWrapper(4,
                32,
                16,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(1000),
                new MyThreadFactory("wxSchoolSyncExecutorPool"),
                new ThreadPoolExecutor.AbortPolicy()
        );

    }


    @Bean(name = "lexingSyncExecutorService", autowire = Autowire.BY_NAME)
    public ExecutorService LexingSyncExecutorService() {
        return new ThreadPoolExecutorMdcWrapper(1, 4, 1000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(32));

    }
}
